﻿<%@ WebHandler Language="C#" Class="RbCompleteSetRateDashBoard" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Net;

/*
 * Description: 热表厂齐套性检查看板
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2024.9.10
 */

public class RbCompleteSetRateDashBoard : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                DataTable dtResult = new DataTable();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getChartData":
                        r = getChartData(jObject);//查询统计数据
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getData":
                        r = getData(jObject);//主界面表格数据
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDetail":
                        r = getDetail(jObject);//对话框明细数据
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//主界面导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    Result getData(JObject jObject)
    {
        string sql = getSql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    Result getChartData(JObject jObject)
    {
        string sql = @"
SELECT SUM(t.iscompworkflow) workflow,
       ROUND(SUM(t.iscompworkflow)/COUNT(1),4) * 100 workflowrate,
       SUM(t.iscompaps) aps,
       ROUND(SUM(t.iscompaps)/COUNT(1),4) * 100 apsrate,
       SUM(t.iscompmaterial) material,
       ROUND(SUM(t.iscompmaterial)/COUNT(1),4) * 100 materialrate,
       SUM(t.iscompresource) resources,
       ROUND(SUM(t.iscompresource)/COUNT(1),4) * 100 resourcesrate,
       SUM(t.iscompspotcheck) spotcheck,
       ROUND(SUM(t.iscompspotcheck)/COUNT(1),4) * 100 spotcheckrate,
       SUM(t.iscomptool) tool,
       ROUND(SUM(t.iscomptool)/COUNT(1),4) * 100 toolrate,
       COUNT(1) total
FROM ({0}) t";
        sql = string.Format(sql, getSql(jObject));
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dtResult.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    // 查询未齐套明细
    Result getDetail(JObject jObject)
    {
        string sql = getSql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    string getSql(JObject obj)
    {
        string factoryid = "", workcenterid = "", teamid = "";
        JArray selectOrg = JArray.Parse(obj["selectOrg"].ToString());
        if (selectOrg.Count == 3)
        {
            factoryid = selectOrg[0].ToString();
            workcenterid = selectOrg[1].ToString();
            teamid = selectOrg[2].ToString();
        }
        else if (selectOrg.Count == 2)
        {
            factoryid = selectOrg[0].ToString();
            workcenterid = selectOrg[1].ToString();
        }
        else
        {
            factoryid = selectOrg[0].ToString();
        }
        string sql = @"
SELECT f.factoryname,f2.factoryname fromfactoryname,cci.containername,ws.workflowstepname,wfb.workflowname,wf.workflowrevision,aps.starttime,w.workcentername,te.teamname,
       t.iscompaps,t.iscompmaterial,t.iscompresource,t.iscompspotcheck,t.iscomptool,t.iscompworkflow,
       DECODE(t.iscompaps,1,'是','否') aps,
       DECODE(t.iscompmaterial,1,'是','否') material,
       DECODE(t.iscompresource,1,'是','否') resources,
       DECODE(t.iscompspotcheck,1,'是','否') spotcheck,
       DECODE(t.iscomptool,1,'是','否') tool,
       DECODE(t.iscompworkflow,1,'是','否') workflow
FROM shipconcompleteset t
INNER JOIN apsplandetail aps ON t.containerid = aps.containerid AND aps.workflowstepid = t.workflowstepid AND aps.isuse = 0
LEFT JOIN factory f ON f.factoryid = aps.specfactoryid
LEFT JOIN containercurrentinfo cci ON cci.containerid = t.containerid
LEFT JOIN workflowstep ws ON ws.workflowstepid = t.workflowstepid
LEFT JOIN workcenter w ON w.workcenterid = aps.workcenterid
LEFT JOIN team te ON te.teamid = aps.teamid
LEFT JOIN factory f2 ON f2.factoryid = cci.originalfactoryid
LEFT JOIN workflow wf ON wf.workflowid = ws.workflowid
LEFT JOIN workflowbase wfb ON wfb.workflowbaseid = wf.workflowbaseid
WHERE 1=1";
        if (factoryid != "")
        {
            sql += string.Format(" AND aps.specfactoryid = '{0}'", factoryid);
        }
        if (workcenterid != "")
        {
            sql += string.Format(" AND w.workcenterid = '{0}'", workcenterid);
        }
        if (teamid != "")
        {
            sql += string.Format(" AND te.teamid = '{0}'", teamid);
        }
        // 转工计划开始
        if (obj["selectdate"] != null && obj["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(obj["selectdate"].ToString());
            sql += string.Format(" AND TRUNC(aps.starttime) >= TO_DATE('{0}','yyyy-mm-dd') + 2 ", arr[0].ToString());
            sql += string.Format(" AND TRUNC(aps.starttime) <= TO_DATE('{0}','yyyy-mm-dd') + 2 ", arr[1].ToString());
        }

        if (obj["status"] != null && obj["status"].ToString() == "未齐套")
        {
            sql += string.Format(" AND t.iscompaps + t.iscompmaterial + t.iscompresource + t.iscompspotcheck + t.iscomptool + t.iscompworkflow < 6");
        }

        if (obj["seriesName"] != null)
        {
            string seriesName = obj["seriesName"].ToString();
            if (seriesName == "workflowrate")
            {
                sql += " AND t.iscompworkflow = 0";
            }
            if (seriesName == "apsrate")
            {
                sql += " AND t.iscompaps = 0";
            }
            if (seriesName == "toolrate")
            {
                sql += " AND t.iscomptool = 0";
            }
            if (seriesName == "materialrate")
            {
                sql += " AND t.iscompmaterial = 0";
            }
            if (seriesName == "resourcesrate")
            {
                sql += " AND t.iscompresource = 0";
            }
            if (seriesName == "spotcheckrate")
            {
                sql += " AND t.iscompspotcheck = 0";
            }
        }
        return sql;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getSql(jObject);
        DataTable dt = dal.GetDataTable(sql);

        dt.Columns.Remove("factoryname");
        dt.Columns.Remove("workcentername");
        dt.Columns.Remove("teamname");
        dt.Columns.Remove("iscompaps");
        dt.Columns.Remove("iscompmaterial");
        dt.Columns.Remove("iscompresource");
        dt.Columns.Remove("iscompspotcheck");
        dt.Columns.Remove("iscomptool");
        dt.Columns.Remove("iscompworkflow");

        dt.Columns["containername"].Caption = "批次号";
        dt.Columns["workflowstepname"].Caption = "工序";
        dt.Columns["fromfactoryname"].Caption = "主制厂";
        dt.Columns["starttime"].Caption = "转工计划开始时间";
        dt.Columns["aps"].Caption = "排产数据齐套";
        dt.Columns["material"].Caption = "生产物资齐套";
        dt.Columns["resources"].Caption = "设备状态齐套";
        dt.Columns["spotcheck"].Caption = "特殊过程齐套";
        dt.Columns["tool"].Caption = "工装工具齐套";
        dt.Columns["workflow"].Caption = "工艺路线齐套";
        dt.Columns["workflowname"].Caption = "工艺路线";
        dt.Columns["workflowrevision"].Caption = "工艺路线版本";
        ExportHelper.ExportExcel(dt, "齐套性检查看板导出");
    }
}